package org.jeecg.modules.wlhy.mbshipping.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.third.digitalseal.utils.PdfToImageUtil;
import org.jeecg.modules.third.daikai.mabang.dto.MbWaybillDTO;
import org.jeecg.modules.third.daikai.mabang.service.MaBangApiService;
import org.jeecg.modules.wlhy.bill.entity.HyShippingNoteBill;
import org.jeecg.modules.wlhy.bill.service.IHyShippingNoteBillService;
import org.jeecg.modules.wlhy.mbshipping.entity.HyMbShipping;
import org.jeecg.modules.wlhy.mbshipping.entity.MaBangUpDataShippingNoteDTO;
import org.jeecg.modules.wlhy.mbshipping.mapper.HyMbShippingMapper;
import org.jeecg.modules.wlhy.mbshipping.service.IHyMbDriverService;
import org.jeecg.modules.wlhy.mbshipping.service.IHyMbShippingService;
import org.jeecg.modules.wlhy.mbshipping.service.IHyMbVehicleService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Description: hy_mb_shipping
 * @Author: duanlikao
 * @Date:   2022-12-19
 * @Version: V1.0
 */
@Service
@Slf4j
public class HyMbShippingServiceImpl extends ServiceImpl<HyMbShippingMapper, HyMbShipping> implements IHyMbShippingService {


    @Resource
    private  MaBangApiService  maBangApiService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyShippingNoteBillService hyShippingNoteBillService;

    @Resource
    private IHyMbDriverService mbDriverService;

    @Resource
    private IHyMbVehicleService mbVehicleService;

    //银行文件路径
    @Value(value = "${jeecg.path.bank}")
    private String bankPath;


    @Override
    public IPage<MaBangUpDataShippingNoteDTO> getMaBangUpDataPageList(Page<MaBangUpDataShippingNoteDTO> page,
                                                                      QueryWrapper<MaBangUpDataShippingNoteDTO> queryWrapper) {
        IPage<MaBangUpDataShippingNoteDTO> pageList = this.baseMapper.getMaBangUpDataPageList(page, queryWrapper);
        return pageList;
    }


    @Override
    public boolean uploadMabang(MaBangUpDataShippingNoteDTO maBangUpDataShippingNoteDTO){

        HyShippingNote shippingNote = hyShippingNoteService.getById(maBangUpDataShippingNoteDTO.getId());
        if (shippingNote == null) {
            throw new JeecgBootException("该运单上报信息不能为空");
        }


        if(!"1".equals( maBangUpDataShippingNoteDTO.getDriverUploadStatus() )){
            mbDriverService.uploadDriver(maBangUpDataShippingNoteDTO.getDriverId());
        }

        if(!"1".equals( maBangUpDataShippingNoteDTO.getVehicleUploadStatus() )){
            mbVehicleService.uploadVehicle(maBangUpDataShippingNoteDTO.getVehicleId());
        }

        LambdaQueryWrapper<HyShippingNoteBill> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HyShippingNoteBill::getShippingId, shippingNote.getId());
        List<HyShippingNoteBill> hyShippingNoteBills = hyShippingNoteBillService.list(queryWrapper);
        if (hyShippingNoteBills.isEmpty()) {
            throw new JeecgBootException("该运单流水单信息不存在！");
        }
        List<String> bankHdImgs = new ArrayList<>();
        for(HyShippingNoteBill hyShippingNoteBill:hyShippingNoteBills){
            String converImageFilePath;
            //银行回单重新生成图片
            if(StringUtils.isNotBlank(hyShippingNoteBill.getBankHd())){
                String bankHd = hyShippingNoteBill.getBankHd() ;
                String[]  pdfStringAarray = bankHd.split("/") ;
                String bankHdname =  pdfStringAarray[pdfStringAarray.length -1];
                //文件名去除后缀
                String filenameNoSubfix = bankHdname.substring(0, bankHdname.lastIndexOf("."));
                String bankHdPath = bankHd.replace(bankHdname,"");
                //回单pdf转jpg
                String filePath =  StringUtils.isNotEmpty(bankHdPath) ?  bankPath + File.separator + bankHdPath : bankPath + File.separator  ;
                converImageFilePath = filePath + PdfToImageUtil.bankHdPdf2Jpg2(filePath, filenameNoSubfix, filePath);
                log.info("重新生成回单文件 {}  ->  {} {}", converImageFilePath, filePath, filenameNoSubfix);
            } else {
                throw new JeecgBootException("该运单银行回单PDF信息不存在！");
            }
            //String bankHdImg = "1".equals(hyShippingNoteBill.getPayChannel()) ? hyShippingNoteBill.getBankHd() : hyShippingNoteBill.getBankHdImg();

            if (StringUtils.isEmpty(converImageFilePath)) {
                throw new JeecgBootException("该运单银行回单图片信息不存在！");
            }
            bankHdImgs.add( maBangApiService.uploadFiles(converImageFilePath, "银行回单") );
        }

        MbWaybillDTO paramDTO =  this.shippingNoteDTOTOMbWaybillDTO(maBangUpDataShippingNoteDTO) ;

        paramDTO.setBankHdImg(
                StringUtils.join(bankHdImgs, ",")
        ); // bankHdImgs.stream().collect(Collectors.joining(","))


        String res = maBangApiService.waybillPush( paramDTO);

        HyMbShipping hyMbShipping = new HyMbShipping();
        hyMbShipping.setShippingId(maBangUpDataShippingNoteDTO.getId());
        hyMbShipping.setUploadTime( new Date());

        if(StringUtils.isBlank(res)){
            hyMbShipping.setUploadStatus("2");
            hyMbShipping.setUploadFailureReason("推送异常");
            this.saveOrUpdateMbShipping(hyMbShipping);
            throw new JeecgBootException("该运单推送异常！");
        }else{
            Result r = JSONObject.parseObject(res,Result.class);
            if(500 == r.getCode()){
                if(r.getMessage().contains("已存在")){
                    hyMbShipping.setUploadStatus("1");
                    this.saveOrUpdateMbShipping(hyMbShipping);
                    return true;
                }
            }

            if (r.isSuccess() && 200 == r.getCode()) {
                hyMbShipping.setUploadStatus("1");
                this.saveOrUpdateMbShipping(hyMbShipping);
                return true;
            }else{
                hyMbShipping.setUploadStatus("2");
                hyMbShipping.setUploadFailureReason(r.getMessage());
                this.saveOrUpdateMbShipping(hyMbShipping);
                throw new JeecgBootException("该运单推送异常 "+r.getMessage());
            }
        }
    }

    public  MbWaybillDTO shippingNoteDTOTOMbWaybillDTO(MaBangUpDataShippingNoteDTO maBangUpDataShippingNoteDTO) {
        if (maBangUpDataShippingNoteDTO == null) {
            return null;
        }
        MbWaybillDTO mbWaybillDTO = new MbWaybillDTO();
        mbWaybillDTO.setDriverName(maBangUpDataShippingNoteDTO.getDriverName());
        mbWaybillDTO.setDriverIdCard(maBangUpDataShippingNoteDTO.getIdcard());
        mbWaybillDTO.setDriverTelephone(maBangUpDataShippingNoteDTO.getTelephone());
        mbWaybillDTO.setVehicleNumber(maBangUpDataShippingNoteDTO.getVehicleNumber());

        mbWaybillDTO.setKhdh(
                maBangUpDataShippingNoteDTO.getShippingNoteNumber()
        );

        mbWaybillDTO.setSendDate(
                DateUtils.dateTimeToString( maBangUpDataShippingNoteDTO.getStatusDtLoading() )
        );

        mbWaybillDTO.setReceiveDate(
                DateUtils.dateTimeToString( maBangUpDataShippingNoteDTO.getStatusDtUnloading() )
        );

        mbWaybillDTO.setWeight(
                maBangUpDataShippingNoteDTO.getGoodsWeightLoading().toString()
        );

        mbWaybillDTO.setShippingUnitPrice(
                maBangUpDataShippingNoteDTO.getCostPayShipping().toString()
        );


        //装卸货榜单
        //List<String> imgLoadingsAll = Arrays.asList(maBangUpDataShippingNoteDTO.getImgLoading().split(","));
        //List<String> imgLoadingsTemp = new ArrayList<>();
        //for(String imgLoading : imgLoadingsAll){
        //    imgLoadingsTemp.add(
        //            maBangApiService.uploadFiles(  imgLoading)
        //    );
        //}
        //
        //
        //mbWaybillDTO.setImgLoading(
        //        StringUtils.join(imgLoadingsTemp, ",")
        //);


        List<String> imgUnloadingsAll = Arrays.asList(maBangUpDataShippingNoteDTO.getImgUnloading().split(","));
        List<String> imgUnloadingsTemp = new ArrayList<>();
        for(String imgUnloading : imgUnloadingsAll){
            imgUnloadingsTemp.add(
                    maBangApiService.uploadFiles(  imgUnloading, "磅单")
            );

        }
        mbWaybillDTO.setImgUnloading(
                StringUtils.join(imgUnloadingsTemp, ",")
        );

        //
        //mbWaybillDTO.setShippingNoteNumber(maBangUpDataShippingNoteDTO.getShippingNoteNumber());
        //mbWaybillDTO.setCustomerId(maBangUpDataShippingNoteDTO.getCustomerId());
        //mbWaybillDTO.setOrderId(maBangUpDataShippingNoteDTO.getOrderId());
        //
        //mbWaybillDTO.setDriverId(maBangUpDataShippingNoteDTO.getDriverId());
        //mbWaybillDTO.setVehicleId(maBangUpDataShippingNoteDTO.getVehicleId());

        //mbWaybillDTO.setGoodsWeightLoading(maBangUpDataShippingNoteDTO.getGoodsWeightLoading());

        //mbWaybillDTO.setGoodsWeightUnloading(maBangUpDataShippingNoteDTO.getGoodsWeightUnloading());
        //mbWaybillDTO.setGoodsWeightLoss(maBangUpDataShippingNoteDTO.getGoodsWeightLoss());
        //
        //mbWaybillDTO.setStatusDtReceive(maBangUpDataShippingNoteDTO.getStatusDtReceive()  );
        //mbWaybillDTO.setStatusDtLoading( maBangUpDataShippingNoteDTO.getStatusDtLoading());
        //mbWaybillDTO.setStatusDtUnloading(maBangUpDataShippingNoteDTO.getStatusDtUnloading());
        //mbWaybillDTO.setStatusDtSign(maBangUpDataShippingNoteDTO.getStatusDtSign());
        //
        //mbWaybillDTO.setPayDtSubmitCheck(maBangUpDataShippingNoteDTO.getPayDtSubmitCheck());
        //mbWaybillDTO.setPayDtCheck(maBangUpDataShippingNoteDTO.getPayDtCheck());
        //mbWaybillDTO.setPayDtSubmitAut(maBangUpDataShippingNoteDTO.getPayDtSubmitAut());
        //mbWaybillDTO.setPayDtAut(maBangUpDataShippingNoteDTO.getPayDtAut());
        //
        //mbWaybillDTO.setPayDt(maBangUpDataShippingNoteDTO.getPayDt());
        //
        //mbWaybillDTO.setBillStatus(maBangUpDataShippingNoteDTO.getBillStatus());
        //mbWaybillDTO.setBillDtRequest(maBangUpDataShippingNoteDTO.getBillDtRequest());
        //mbWaybillDTO.setBillDtComplate(maBangUpDataShippingNoteDTO.getBillDtComplate());


        //mbWaybillDTO.setRemark(maBangUpDataShippingNoteDTO.getRemark());
        //
        //mbWaybillDTO.setLossGoodsUnitPrice(maBangUpDataShippingNoteDTO.getLossGoodsUnitPrice());

        //mbWaybillDTO.setShippingUnitPrice(maBangUpDataShippingNoteDTO.getShippingUnitPrice());

        //mbWaybillDTO.setLossType(maBangUpDataShippingNoteDTO.getLossType());
        //mbWaybillDTO.setLossProportion(maBangUpDataShippingNoteDTO.getLossProportion());
        //mbWaybillDTO.setCostLoss(maBangUpDataShippingNoteDTO.getCostLoss());
        //mbWaybillDTO.setCostPay(maBangUpDataShippingNoteDTO.getCostPay());
        //mbWaybillDTO.setPreType(maBangUpDataShippingNoteDTO.getPreType());
        //mbWaybillDTO.setPrePayStatus(maBangUpDataShippingNoteDTO.getPrePayStatus());
        //mbWaybillDTO.setPrePayChannel(maBangUpDataShippingNoteDTO.getPrePayChannel());
        //mbWaybillDTO.setPrePayDt(maBangUpDataShippingNoteDTO.getPrePayDt());
        //mbWaybillDTO.setPreUnitFee(maBangUpDataShippingNoteDTO.getPreUnitFee());
        //mbWaybillDTO.setPreFee(maBangUpDataShippingNoteDTO.getPreFee());
        //mbWaybillDTO.setPrePaySource(maBangUpDataShippingNoteDTO.getPrePaySource());
        //mbWaybillDTO.setBillPrePayStatus(maBangUpDataShippingNoteDTO.getBillPrePayStatus());
        //mbWaybillDTO.setCostPayShipping(maBangUpDataShippingNoteDTO.getCostPayShipping());

       // mbWaybillDTO.setDriverFee(maBangUpDataShippingNoteDTO.getDriverFee());

        //mbWaybillDTO.setCostService(maBangUpDataShippingNoteDTO.getCostService());
        //mbWaybillDTO.setCostPayTotal(maBangUpDataShippingNoteDTO.getCostPayTotal());
        //mbWaybillDTO.setCustomerFee(maBangUpDataShippingNoteDTO.getCustomerFee());
        //mbWaybillDTO.setAgentId(maBangUpDataShippingNoteDTO.getAgentId());
        //mbWaybillDTO.setAgentPrice(maBangUpDataShippingNoteDTO.getAgentPrice());
        //mbWaybillDTO.setAgentCostPay(maBangUpDataShippingNoteDTO.getAgentCostPay());
        //mbWaybillDTO.setAgentCostPayShipping(maBangUpDataShippingNoteDTO.getAgentCostPayShipping());
        //mbWaybillDTO.setAgentCostPayTotal(maBangUpDataShippingNoteDTO.getAgentCostPayTotal());
        //mbWaybillDTO.setAgentFee(maBangUpDataShippingNoteDTO.getAgentFee());
        mbWaybillDTO.setPayType(maBangUpDataShippingNoteDTO.getPayType());
        mbWaybillDTO.setCarrierId(maBangUpDataShippingNoteDTO.getCarrierId());
        //mbWaybillDTO.setCarrierFeeType(maBangUpDataShippingNoteDTO.getCarrierFeeType());
        //mbWaybillDTO.setCarrierUnitFee(maBangUpDataShippingNoteDTO.getCarrierUnitFee());
        //mbWaybillDTO.setCarrierFee(maBangUpDataShippingNoteDTO.getCarrierFee());
        //mbWaybillDTO.setInvoiceId(maBangUpDataShippingNoteDTO.getInvoiceId());
        //mbWaybillDTO.setInvoiceImg(maBangUpDataShippingNoteDTO.getInvoiceImg());
        //mbWaybillDTO.setEvaluationId(maBangUpDataShippingNoteDTO.getEvaluationId());
        //mbWaybillDTO.setCompanyId(maBangUpDataShippingNoteDTO.getCompanyId());
        //mbWaybillDTO.setQsr(maBangUpDataShippingNoteDTO.getQsr());
        //mbWaybillDTO.setDzr(maBangUpDataShippingNoteDTO.getDzr());
        //mbWaybillDTO.setShrr(maBangUpDataShippingNoteDTO.getShrr());
        //mbWaybillDTO.setFkr(maBangUpDataShippingNoteDTO.getFkr());
        //mbWaybillDTO.setBillPayStatus(maBangUpDataShippingNoteDTO.getBillPayStatus());
        //mbWaybillDTO.setBillPayRemark(maBangUpDataShippingNoteDTO.getBillPayRemark());
        //mbWaybillDTO.setIzUsedGas(maBangUpDataShippingNoteDTO.getIzUsedGas());
        //mbWaybillDTO.setGasRechargeAmount(maBangUpDataShippingNoteDTO.getGasRechargeAmount());
        //
        //mbWaybillDTO.setShippingType(maBangUpDataShippingNoteDTO.getShippingType());
        //mbWaybillDTO.setShippingContract(maBangUpDataShippingNoteDTO.getShippingContract());
        //mbWaybillDTO.setShippingContract2(maBangUpDataShippingNoteDTO.getShippingContract2());
        //
        //mbWaybillDTO.setIzServiceOpenInvoicing(maBangUpDataShippingNoteDTO.getIzServiceOpenInvoicing());
        //mbWaybillDTO.setTransportationDistance(maBangUpDataShippingNoteDTO.getTransportationDistance());
        //
        //mbWaybillDTO.setContractNum(maBangUpDataShippingNoteDTO.getContractNum());
        //mbWaybillDTO.setContractNum2(maBangUpDataShippingNoteDTO.getContractNum2());
        //mbWaybillDTO.setContractType(maBangUpDataShippingNoteDTO.getContractType());
        //mbWaybillDTO.setContractStatus(maBangUpDataShippingNoteDTO.getContractStatus());
        //mbWaybillDTO.setContractOr(maBangUpDataShippingNoteDTO.getContractOr());
        //mbWaybillDTO.setAddressSendId(maBangUpDataShippingNoteDTO.getAddressSendId());

       // mbWaybillDTO.setSendDate(maBangUpDataShippingNoteDTO.getSendDate());


        //mbWaybillDTO.setSendAddressName(maBangUpDataShippingNoteDTO.getSendAddressName());
        //mbWaybillDTO.setSendLongitude(maBangUpDataShippingNoteDTO.getSendLongitude());
        //mbWaybillDTO.setSendLatitude(maBangUpDataShippingNoteDTO.getSendLatitude());
        mbWaybillDTO.setSendAddress(maBangUpDataShippingNoteDTO.getSendAddress());
        //mbWaybillDTO.setSendAreaCode(maBangUpDataShippingNoteDTO.getSendAreaCode());
        //mbWaybillDTO.setSendContactName(maBangUpDataShippingNoteDTO.getSendContactName());
        //mbWaybillDTO.setSendContactTel(maBangUpDataShippingNoteDTO.getSendContactTel());
        //mbWaybillDTO.setAddressReceiveId(maBangUpDataShippingNoteDTO.getAddressReceiveId());

       // mbWaybillDTO.setReceiveDate(maBangUpDataShippingNoteDTO.getReceiveDate());

        //mbWaybillDTO.setReceiveAddressName(maBangUpDataShippingNoteDTO.getReceiveAddressName());
        //mbWaybillDTO.setReceiveLongitude(maBangUpDataShippingNoteDTO.getReceiveLongitude());
        //mbWaybillDTO.setReceiveLatitude(maBangUpDataShippingNoteDTO.getReceiveLatitude());
        mbWaybillDTO.setReceiveAddress(maBangUpDataShippingNoteDTO.getReceiveAddress());
        //mbWaybillDTO.setReceiveAreaCode(maBangUpDataShippingNoteDTO.getReceiveAreaCode());
        //mbWaybillDTO.setReceiveContactName(maBangUpDataShippingNoteDTO.getReceiveContactName());
        //mbWaybillDTO.setReceiveContactTel(maBangUpDataShippingNoteDTO.getReceiveContactTel());
        //mbWaybillDTO.setBusinessTypeCode(maBangUpDataShippingNoteDTO.getBusinessTypeCode());
        //mbWaybillDTO.setGoodsUnit(maBangUpDataShippingNoteDTO.getGoodsUnit());
        mbWaybillDTO.setDescriptionOfGoods(maBangUpDataShippingNoteDTO.getDescriptionOfGoods());
        mbWaybillDTO.setCargoTypeClassificationCode(maBangUpDataShippingNoteDTO.getCargoTypeClassificationCode());
        //mbWaybillDTO.setCube(maBangUpDataShippingNoteDTO.getCube());
        //
        //mbWaybillDTO.setPayChannel(maBangUpDataShippingNoteDTO.getPayChannel());
        //mbWaybillDTO.setPayRecordId(maBangUpDataShippingNoteDTO.getPayRecordId());
        //mbWaybillDTO.setPrePayRecordId(maBangUpDataShippingNoteDTO.getPrePayRecordId());
        //mbWaybillDTO.setPlatformCostId(maBangUpDataShippingNoteDTO.getPlatformCostId());
        //mbWaybillDTO.setDriverBankId(maBangUpDataShippingNoteDTO.getDriverBankId());
        //mbWaybillDTO.setUnloadingFee(maBangUpDataShippingNoteDTO.getUnloadingFee());
        //mbWaybillDTO.setInformationFee(maBangUpDataShippingNoteDTO.getInformationFee());
        //mbWaybillDTO.setServiceFee(maBangUpDataShippingNoteDTO.getServiceFee());
        //mbWaybillDTO.setPenalty(maBangUpDataShippingNoteDTO.getPenalty());
        //mbWaybillDTO.setPenaltyReason(maBangUpDataShippingNoteDTO.getPenaltyReason());
        //mbWaybillDTO.setPaySource(maBangUpDataShippingNoteDTO.getPaySource());
        //mbWaybillDTO.setBz(maBangUpDataShippingNoteDTO.getBz());
        //mbWaybillDTO.setUnloadingBz(maBangUpDataShippingNoteDTO.getUnloadingBz());
        //
        //mbWaybillDTO.setDispatcher(maBangUpDataShippingNoteDTO.getDispatcher());
        //mbWaybillDTO.setModifyFreightStatus(maBangUpDataShippingNoteDTO.getModifyFreightStatus());
        return mbWaybillDTO;
    }



    @Override
    public boolean saveOrUpdateMbShipping(HyMbShipping hyMbShipping){
        try {
            hyMbShipping.setId(hyMbShipping.getShippingId());
            return this.saveOrUpdate(hyMbShipping);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }
}
